<?php

namespace App\Services;

use App\Exceptions\AuthException;
use App\Exceptions\FobbidenException;
use App\Models\FeedbackModel;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Model;

class FeedbackService extends BaseService
{
    const COLUMNS = ['id', 'user_id', 'title', 'title', 'content', 'created_at'];

    /**
     * 获取留言分页数据
     *
     * @param int $page_size 每页条数
     * @return LengthAwarePaginator
     */
    public function getPaginatedFeedback(int $page_size): LengthAwarePaginator
    {
        $data = FeedbackModel::query()
            ->select(self::COLUMNS)
            ->where('deleted_at', 0)
            ->with(['user' => function ($q) {
                $q->select('id', 'name');
            }])
            ->paginate($page_size ?: self::PAGE_SIZE);

        foreach ($data as $datum) {
            $datum->setAttribute('formatted_time', timeTransfer($datum->created_at));
        }

        return $data;
    }

    private function transferColumns(array $data): array
    {
        $user = auth()->user();

        return [
            'user_id' => $user->id ?? 0,
            'title' => $data['title'] ?? '',
            'content' => $data['content'] ?? '',
            'created_at' => time(),
            'updated_at' => time()
        ];
    }

    /**
     * 添加留言
     *
     * @param array $data
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     * @throws AuthException
     * @throws FobbidenException
     */
    public function storeFeedback(array $data)
    {
        $user = auth()->user();
        if (! $user) {
            throw new AuthException('请先登录', 401);
        }

        $blacklist = (new BlacklistService())->ifInBlacklist($user->id);
        if ($blacklist) {
            throw new FobbidenException('您已被加入黑名单，禁止添加留言', 403);
        }

        $temp = $this->transferColumns($data);

        return FeedbackModel::query()->create($temp);
    }

    /**
     * 查询留言
     *
     * @param int $feedback_id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getFeedbackById(int $feedback_id)
    {
        return FeedbackModel::query()
            ->select(self::COLUMNS)
            ->where('deleted_at', 0)
            ->where('id', $feedback_id)
            ->first();
    }

    public function countFeedback(): int
    {
        return FeedbackModel::query()
            ->select('id')
            ->where('deleted_at', 0)
            ->count();
    }
}
